package com.xtq.springcloud.controller;

import com.xtq.springcloud.entity.Member;
import com.xtq.springcloud.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: xietianqi
 * @create: 2024-01-23 09:36
 * @description: 这个是80端口打的服务
 **/

@Slf4j
@RestController
public class MemberConsumerController {
	// 定义member_service_provider_url
	// 需要注配置负载均衡算法@LoadBanlanced  轮询算法默认
	public static final String MEMBER_SERVICE_PROVIDER_URL = "http://MEMBER-SERVICE-PROVIDER";
	
	// 装配
	@Resource
	private RestTemplate restTemplate;
	
	// 装配DiscoveryClient
	@Resource
	private DiscoveryClient discoveryClient;
	
	/**
	 * 请求10000这个服务
	 *
	 * @param member
	 * @return 因为没有给参数家@RequestBody按理来说应该用参数,表单提交,但实际上不可以成功因为在调用其他微服务时需要RestTemplate[对象的形式调用]底层其实是json格式的!!
	 * 所以必须在被调用的接口处指定json格式的注解
	 */
	@PostMapping("/member/consumer/save")
	public Result<Member> save(Member member) {
		// 要在这里看一下
		log.info("service-consumer member={}", member);
		return restTemplate.postForObject(MEMBER_SERVICE_PROVIDER_URL + "/member/save", member, Result.class);
	}
	
	@GetMapping("/member/consumer/{id}")
	public Result<Member> getMemberById(@PathVariable("id") Long id) {
		return restTemplate.getForObject(MEMBER_SERVICE_PROVIDER_URL + "/member/get/" + id, Result.class);
	}
	
	/**
	 * discovery用于打印测试的调用数据
	 *
	 * @return
	 */
	@GetMapping("/member/consumer/discovery")
	public Object discovery() {
		List<String> services = discoveryClient.getServices();
		for (String service : services) {
			log.info("服务名={}", service);
			// 通过服务名获取实例
			List<ServiceInstance> instances = discoveryClient.getInstances(service);
			for (ServiceInstance instance : instances) {
				log.info("id={},host={},port={},uri={}", instance.getInstanceId(), instance.getHost(), instance.getPort(), instance.getUri());
			}
			
		}
		return discoveryClient;
	}
	
}
